The following a better formatted and slightly changed version of the coding style document available here. (In the original document some of the examples were unreadable). I only made small changes to the actual contents of it which were either outdated / I did not agree with. All credit goes to the original author and references.
This document lists C++ coding recommendations common in the C++ development community.
The recommendations are based on established standards collected from a number of sources, individual experience, local requirements/needs, as well as suggestions given in the references section.
There are several reasons for introducing a new guideline rather than just referring to the ones above. The main reason is that these guides are far too general in their scope and that more specific rules (especially naming rules) need to be established. Also, the present guide has an annotated form that makes it far easier to use during project code reviews than most other existing guidelines. In addition, programming recommendations generally tend to mix style issues with language technical issues in a somewhat confusing manner. The present document does not contain any C++ technical recommendations at all, but focuses mainly on programming style. For guidelines on C++ programming style refer to the C++ Programming Practice Guidelines.
While a given development environment (IDE) can improve the readability of code by access visibility, colour coding, automatic formatting and so on, the programmer should never rely on such features. Source code should always be considered larger than the IDE it is developed within and should be written in a way that maximise its readability independent of any IDE.
The recommendations are grouped by topic and each recommendation is numbered to make it easier to refer to during reviews.
Layout of the recommendations is as follows:
| n. Guideline short description |
|---|
| Example if applicable |
| Motivation, background and additional information. |
The motivation section is important. Coding standards and guidelines tend to start "religious wars", and it is important to state the background for the recommendation.
In the guideline sections the terms must, should and can have special meaning. A must requirement must be followed, a should is a strong recommendation, and a can is a general guideline.
The main goal of the recommendation is to improve readability and thereby the understanding and the maintainability and general quality of the code. It is impossible to cover all the specific cases in a general guide and the programmer should be flexible.
The attempt is to make a guideline, not to force a particular coding style onto individuals. Experienced programmers normally want to adopt a style like this anyway, but having one, and at least requiring everyone to get familiar with it, usually makes people start thinking about programming style and evaluate their own habits in this area.
On the other hand, new and inexperienced programmers normally use a style guide as a convenience of getting into the programming jargon more easily.
1Line, SavingsAccount
Common practice in the C++ development community.
1line, savingsAccount
Common practice in the C++ development community. Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line;
1MAX_ITERATIONS, COLOR_RED, PI
Common practice in the C++ development community. In general, the use of such constants should be minimized. In many cases implementing the value as a method is a better choice:
1int getMaxIterations() // NOT: MAX_ITERATIONS = 25
2{
3 return 25;
4}
This form is both easier to read, and it ensures a unified interface towards class values.
1getName(), computeTotalWidth()
Common practice in the C++ development community. This is identical to variable names, but functions in C++ are already distingushable from variables by their specific form.
1model::analyzer, io::iomanager, common::math::geometry
Common practice in the C++ development community.
##### 3.1.6 Names representing template types should be a single uppercase letter.
1template<class T> ...
2template<class C, class D> ...
Common practice in the C++ development community. This makes template names stand out relative to all other names used.
1exportHtmlSource(); // NOT: exportHTMLSource();
2openDvdPlayer(); // NOT: openDVDPlayer();
Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type would have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readability is seriously reduced; the word following the abbreviation does not stand out as it should.
1::mainWindow.open(), ::applicationContext.getName()
In general, the use of global variables should be avoided. Consider using singleton objects instead.
1class SomeClass {
2private:
3 int length_;
4}
Apart from its name and its type, the scope of a variable is its most important feature. Indicating class scope by using underscore makes it easy to distinguish class variables from local scratch variables. This is important because class variables are considered to have higher significance than method variables, and should be treated with special care by the programmer.
A side effect of the underscore naming convention is that it nicely resolves the problem of finding reasonable variable names for setter methods and constructors:
1void setDepth (int depth)
2{
3 depth_ = depth;
4}
An issue is whether the underscore should be added as a prefix or as a suffix. Both practices are commonly used, but the latter is recommended because it seem to best preserve the readability of the name.
It should be noted that scope identification in variables has been a controversial issue for quite some time. It seems, though, that this practice now is gaining acceptance and that it is becoming more and more common as a convention in the professional development community.
1void setTopic(Topic* topic)
2// NOT: void setTopic(Topic* value)
3// NOT: void setTopic(Topic* aTopic)
4// NOT: void setTopic(Topic* t)
5
6void connect(Database* database)
7// NOT: void connect(Database* db)
8// NOT: void connect (Database* oracleDB)
Reduce complexity by reducing the number of terms and names used. Also makes it easy to deduce the type given a variable name only.
If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen.
Non-generic variables have a role. These variables can often be named by combining role and type:
1Point startingPoint, centerPoint;
2Name loginName;
1fileName; // NOT: filNavn
English is the preferred language for international development.
Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables should be able to assume that its value is not used outside of a few lines of code. Common scratch variables for integers are i, j, k, m, n and for characters c and d.
1line.getLength();
2// NOT: line.getLineLength();
The latter seems natural in the class declaration, but proves superfluous in use, as shown in the example.
1employee.getName();
2employee.setName(name);
3matrix.getElement(2, 4);
4matrix.setElement(2, 4, value);
Common practice in the C++ development community. In Java this convention has become more or less standard.
1valueSet->computeAverage();
2matrix->computeInverse()
Give the reader the immediate clue that this is a potentially time-consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.
1vertex.findNearestVertex();
2matrix.findMinElement();
Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability.
1printer.initializeFontSet();
The American initialize should be preferred over the English initialise. Abbreviation init should be avoided.
1mainWindow, propertiesDialog, widthScale, loginText, leftScrollbar, mainForm, fileMenu, minLabel, exitButton, yesToggle // etc.
Enhances readability since the name gives the user an immediate clue of the type of the variable and thereby the objects resources.
1vector<Point> points;
2int values[];
Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.
1nPoints, nLines
The notation is taken from mathematics where it is an established convention for indicating a number of objects.
1tableNo, employeeNo
The notation is taken from mathematics where it is an established convention for indicating an entity number.
An elegant alternative is to prefix such variables with an i: iTable, iEmployee. This effectively makes them named iterators.
1for (int i = 0; i < nTables); i++) { }
2for (vector<MyClass>::iterator i = list.begin(); i != list.end(); i++) { Element element = *i; ... }
The notation is taken from mathematics where it is an established convention for indicating iterators.
Variables named j, k etc. should be used for nested loops only.
1isSet, isVisible, isFinished, isFound, isOpen
Common practice in the C++ development community and partially enforced in Java.
Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to choose more meaningful names.
There are a few alternatives to the is prefix that fit better in some situations. These are the has, can and should prefixes:
1bool hasLicense();
2bool canEvaluate();
3bool shouldSort();
1get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, // etc.
Reduce complexity by symmetry.
1computeAverage(); // NOT: compAvg();
There are two types of words to consider. First are the common words listed in a language dictionary. These must never be abbreviated. Never write:
cmd instead of command
cp instead of copy
pt instead of point
comp instead of compute
init instead of initialize
etc.
Then there are domain specific phrases that are more naturally known through their abbreviations/acronym. These phrases should be kept abbreviated. Never write:
HypertextMarkupLanguage instead of html
CentralProcessingUnit instead of cpu
PriceEarningRatio instead of pe
etc.
1Line* line;
2// NOT: Line* pLine;
3// NOT: Line* linePtr;
Many variables in a C/C++ environment are pointers, so a convention like this is almost impossible to follow. Also objects in C++ are often oblique types where the specific implementation should be ignored by the programmer. Only when the actual type of an object is of special significance, the name should emphasize the type.
1bool isError; // NOT: isNoError
2bool isFound; // NOT: isNotFound
The problem arises when such a name is used in conjunction with the logical negation operator as this results in a double negative. It is not immediately apparent what !isNotFound means.
1enum Color { COLOR_RED, COLOR_GREEN, COLOR_BLUE };
This gives additional information of where the declaration can be found, which constants belongs together, and what concept the constants represent.
An alternative approach is to always refer to the constants through their common type: Color::RED, Airline::AIR_FRANCE etc.
Note also that the enum name typically should be singular as in enum Color {...}. A plural name like enum Colors {...} may look fine when declaring the type, but it will look silly in use.
1class AccessException { ... }
Exception classes are really not part of the main design of the program, and naming them like this makes them stand out relative to the other classes.
Increase readability. Makes it clear what the unit should do and especially all the things it is not supposed to do. This again makes it easier to keep the code clean of side effects.
1MyClass.cpp, MyClass.h
These are all accepted C++ standards for file extension.
1MyClass.h, MyClass.cpp
Makes it easy to find the associated files of a given class. An obvious exception is template classes that must be both declared and defined inside a .h file.
The header files should declare an interface, the source file should implement it. When looking for an implementation, the programmer should always know that it is found in the source file.
80 columns is a common dimension for editors, terminal emulators, printers and debuggers, and files that are shared between several people should keep within these constraints. It improves readability when unintentional line breaks are avoided when passing a file between programmers.
These characters are bound to cause problem for editors, printers, terminal emulators or debuggers when used in a multi-programmer, multi-platform environment.
1totalSum = a + b + c + d +
2 e;
3function (param1, param2,
4 param3);
5setText ("Long line split"
6 "into two parts.");
7for (int tableNo = 0; tableNo < nTables;
8 tableNo += tableStep) { ... }
Split lines occurs when a statement exceed the 80 column limit given above. It is difficult to give rigid rules for how lines should be split, but the examples above should give a general hint.
In general: - Break after a comma. - Break after an operator. - Align the new line with the beginning of the expression on the previous line.
1#ifndef COM_COMPANY_MODULE_CLASSNAME_H
2#define COM_COMPANY_MODULE_CLASSNAME_H
3...
4#endif // COM_COMPANY_MODULE_CLASSNAME_H
The construction is to avoid compilation errors. The name convention resembles the location of the file inside the source tree and prevents naming conflicts.
1#include <fstream>
2#include <iomanip>
3
4#include <qt/qbutton.h>
5#include <qt/qtextfield.h>
6
7#include "com/company/ui/PropertiesDialog.h"
8#include "com/company/ui/MainWindow.h"
In addition to show the reader the individual include files, it also give an immediate clue about the modules that are involved.
Include file paths must never be absolute. Compiler directives should instead be used to indicate root directories for includes.
Common practice. Avoid unwanted compilation side effects by "hidden" include statements deep into a source file.
Enforces information hiding.
The ordering is "most public first" so people who only wish to use the class can stop reading when they reach the protected/private sections.
1floatValue = static_cast<float>(intValue); // NOT: floatValue = intValue;
By this, the programmer indicates that he is aware of the different types involved and that the mix is intentional.
This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a valid value where it is declared:
1int x, y, z;
2getCenter(&x, &y, &z);
In these cases it should be left uninitialized rather than initialized to some phony value.
Enhance readability by ensuring all concepts are represented uniquely. Reduce chance of error by side effects.
In C++ there is no reason global variables need to be used at all. The same is true for global functions or file scope (static) variables.
The concept of C++ information hiding and encapsulation is violated by public variables. Use private variables and access functions instead. One exception to this rule is when the class is essentially a data structure, with no behavior (equivalent to a C struct). In this case it is appropriate to make the class' instance variables public [2].
Note that structs are kept in C++ for compatibility with C only, and avoiding them increases the readability of the code by reducing the number of constructs used. Use a class instead.
1float* x; // NOT: float *x;
2int& y; // NOT: int &y;
The pointer-ness or reference-ness of a variable is a property of the type rather than the name. C-programmers often use the alternative approach, while in C++ it has become more common to follow this recommendation.
1if (nLines != 0) // NOT: if (nLines)
2if (value != 0.0) // NOT: if (value)
It is not necessarily defined by the C++ standard that ints and floats 0 are implemented as binary 0. Also, by using an explicit test the statement gives an immediate clue of the type being tested.
It is common also to suggest that pointers shouldn't test implicitly for 0 either, i.e. if (line == 0) instead of if (line). The latter is regarded so common in C/C++ however that it can be used.
Keeping the operations on a variable within a small scope, it is easier to control the effects and side effects of the variable.
1int sum = 0;
2for (int i = 0; i < 100; i++)
3 sum += value[i];
4
5// NOT:
6// for (int i = 0, int sum = 0; i < 100; i++) sum += value[i];
Increase maintainability and readability. Make a clear distinction of what controls and what is contained in the loop.
1bool isDone = false;
2while (!isDone) { ... }
3
4// NOT:
5// bool isDone = false;
6// ...
7/// while (!isDone) { ... }
do-while loops are less readable than ordinary while loops and for loops since the conditional is at the bottom of the loop. The reader must scan the entire loop in order to understand the scope of the loop.
In addition, do-while loops are not needed. Any do-while loop can easily be rewritten into a while loop or a for loop. Reducing the number of constructs used enhance readbility.
These statements should only be used if they give higher readability than their structured counterparts.
1while (true) { }
2// NOT: for (;;) { }
3// NOT: while (1) { }
Testing against 1 is neither necessary nor meaningful. The form for (;;) is not very readable, and it is not apparent that this actually is an infinite loop.
1bool isFinished = (elementNo < 0) | (elementNo > maxElement);
2bool isRepeatedEntry = elementNo == lastElement;
3if (isFinished | isRepeatedEntry) { }
4
5// NOT:
6// if ((elementNo < 0) | (elementNo > maxElement)| elementNo == lastElement) { }
By assigning boolean variables to expressions, the program gets automatic documentation. The construction will be easier to read, debug and maintain.
1bool isOk = readFile (fileName);
2if (isOk) { }
3else { }
Makes sure that the exceptions don't obscure the normal path of execution. This is important for both the readability and performance.
1if (isDone)
2 doCleanup();
3
4// NOT: if (isDone) doCleanup();
This is for debugging purposes. When writing on a single line, it is not apparent whether the test is really true or not.
1File* fileHandle = open(fileName, "w");
2if (!fileHandle) { }
3
4// NOT:
5// if (!(fileHandle = open(fileName, "w"))) { }
Conditionals with executable statements are just very difficult to read. This is especially true for programmers new to C/C++.
If the number does not have an obvious meaning by itself, the readability is enhanced by introducing a named constant instead. A different approach is to introduce a method from which the constant can be accessed.
1double total = 0.0; // NOT: double total = 0;
2double speed = 3.0e8; // NOT: double speed = 3e8;
3double sum;
4...
5sum = (a + b) * 10.0;
This emphasizes the different nature of integer and floating point numbers. Mathematically the two model completely different and non-compatible concepts.
Also, as in the last example above, it emphasizes the type of the assigned variable (sum) at a point in the code where this might not be evident.
1double total = 0.5; // NOT: double total = .5;
The number and expression system in C++ is borrowed from mathematics and one should adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more readable than .5; There is no way it can be mixed with the integer 5.
1int getValue() { ... } // NOT: getValue() { ... }
If not exlicitly listed, C++ implies int return value for functions. A programmer must never rely on this feature, since this might be confusing for programmers not aware of this artifact.
Goto statements violate the idea of structured code. Only in some very few cases (for instance breaking out of deeply nested structures) should goto be considered, and only if the alternative structured counterpart is proven to be less readable.
NULL is part of the standard C library, but is made obsolete in C++;
1for (i = 0; i < nElements; i++)
2 a[i] = 0;
Indentation of 1 is too small to emphasize the logical layout of the code. Indentation larger than 4 makes deeply nested code difficult to read and increases the chance that the lines must be split. Choosing between indentation of 2, 3 and 4, 2 and 4 are the more common.
1// Example 1:
2while (!done)
3{
4 doSomething();
5 done = moreToDo();
6}
7// Example 2:
8while (!done) {
9 doSomething();
10 done = moreToDo();
11}
12// Example 3:
1class SomeClass : public BaseClass {
2public: ...
3protected: ...
4private: ...
5}
This follows partly from the general block rule above.
1void someMethod() { ... }
This follows from the general block rule above.
1if (condition) {
2 statements;
3}
4
5if (condition) {
6 statements;
7} else {
8 statements;
9
10} if (condition) {
11 statements;
12} else if (condition) {
13 statements;
14} else {
15 statements;
16 }
This follows partly from the general block rule above. The else clause bein on the same line as the closing bracket is considered better in the way that each part of the if-else statement is written on separate lines of the file. This should make it easier to manipulate the statement, for instance when moving else clauses around.
1for (initialization; condition; update) {
2 statements;
3}
This follows from the general block rule above.
1for (initialization; condition; update);
This emphasizes the fact that the for statement is empty and it makes it obvious for the reader that this is intentional. Empty loops should be avoided however.
1while (condition) {
2 statements;
3}
This follows from the general block rule above.
1do {
2 statements;
3} while (condition);
This follows from the general block rule above.
1switch (condition) {
2 case ABC:
3 statements; // Fallthrough
4 case DEF:
5 statements;
6 break;
7 case XYZ:
8 statements;
9 break;
10 default:
11 statements;
12 break;
13}
Note that each case keyword is indented relative to the switch statement as a whole. This makes the entire switch statement stand out. The explicit Fallthrough comment should be included whenever there is a case statement without a break statement. Leaving the break out is a common error, and it must be made clear that it is intentional when it is not there.
1try {
2 statements;
3} catch (Exception& exception) {
4 statements;
5}
This follows partly from the general block rule above. The discussion about closing brackets for if-else statements apply to the try-catch statements.
1if (condition)
2 statement;
3while (condition)
4 statement;
5for (initialization; condition; update)
6 statement;
It is a common recommendation that brackets should always be used in all these cases. However, brackets are in general a language construct that groups several statements. Brackets are per definition superfluous on a single statement. A common argument against this syntax is that the code will break if an additional statement is added without also adding the brackets. In general however, code should never be written to accommodate for changes that might arise.
1void
2MyClass::myMethod(void) { }
This makes it easier to spot function names within a file since they all start in the first column.
1a = (b + c) * d; // NOT: a=(b+c)*d
2
3doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
4
5while (true) // NOT: while(true)
6
7for (i = 0; i < 10; i++) // NOT: for(i=0;i<10;i++)
8
Makes the individual components of the statements stand out. Enhances readability. It is difficult to give a complete list of the suggested use of whitespace in C++ code. The examples above however should give a general idea of the intentions.
1Matrix4x4 matrix = new Matrix4x4();
2double cosAngle = Math.cos(angle);
3double sinAngle = Math.sin(angle);
4
5matrix.setElement(1, 1, cosAngle);
6matrix.setElement(1, 2, sinAngle);
7matrix.setElement(2, 1, -sinAngle);
8matrix.setElement(2, 2, cosAngle);
9
10multiply(matrix);
Enhance readability by introducing white space between logical units of a block.
By making the space larger than space within a method, the methods will stand out within the class.
1AsciiFile* file;
2int nPoints;
3float x, y;
Enhance readability. The variables are easier to spot from the types by alignment.
1if (a == lowValue ) computeSomething();
2else if (a == mediumValue) computeSomethingElse();
3else if (a == highValue ) computeSomethingElseYet();
4
5float value = (potential * oilDensity ) / constant1 +
6 (depth * waterDensity) / constant2 +
7 (zCoordinateValue * gasDensity ) / constant3;
8
9float minPosition = computeDistance(min, x, y, z);
10float averagePosition = computeDistance(average, x, y, z);
11
There are a number of places in the code where white space can be included to enhance readability even if this violates common guidelines. Many of these cases have to do with code alignment. General guidelines on code alignment are difficult to give, but the examples above should give a general clue.
Note that in some cases this approach may interfere with merges or get messed up by refactoring tools.
In general, the use of comments should be minimized by making the code self-documenting by appropriate name choices and an explicit logical structure.
In an international environment English is the preferred language.
1// Comment spanning
2// more than one line.
Since multilevel C-commenting is not supported, using // comments ensure that it is always possible to comment out entire sections of a file using / / for debugging purposes etc.
There should be a space between the "//" and the actual comment, and comments should always start with an upper case letter and end with a period.
1while (true) { // NOT: while (true)
2 // Do something
3 something();
4
5 // Do something
6 something();
7}
This is to avoid that the comments break the logical structure of the program.
Regarding standardized class and method documentation the Java development community is more mature than the C/C++ one. This is due to the standard automatic Javadoc tool that is part of the development kit and that help producing high quality hypertext documentation from these comments.
There are Javadoc-like tools available also for C++. These follows the same tagging syntax as Javadoc. See for instance Doc++ or Doxygen.
[1] Code Complete, Steve McConnell - Microsoft Press
[2] Programming in C++, Rules and Recommendations, M Henricson, e. Nyquist, Ellemtel (Swedish telecom)
http://www.doc.ic.ac.uk/lab/cplus/c%2b%2b.rules/
[3] Wildfire C++ Programming Style, Keith Gabryelski, Wildfire Communications Inc.
http://www.wildfire.com/~ag/Engineering/Development/C++Style/
[4] C++ Coding Standard, Todd Hoff
http://www.possibility.com/Cpp/CppCodingStandard.htm
[5] Doxygen documentation system
http://www.stack.nl/~dimitri/doxygen/index.html
Thanks to Robert P.J. Day for valuable contributions.